package fr.cephb.j2ee.tag;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.List;
import java.util.Map;


import javax.servlet.jsp.JspWriter;

import fr.cephb.json.parser.JSONParser;
import fr.cephb.xml.XML;


public class  JsonTag
	extends AbstractContentTag
	{
    private static final long serialVersionUID = 1L;
    public JsonTag()
            {
            }
    
 
    
    @Override
    public void print(JspWriter out, String content) throws IOException
            {
            try
				{
				JSONParser p=new JSONParser(new StringReader(content));
				Object o= p.any();
				p.eof();
				StringWriter w= new StringWriter();
				echo(o,w);
				out.print(w.toString());
				}
			catch (Throwable e)
				{
				out.print(content);
				}
            }
    @SuppressWarnings("unchecked")
	private void echo(Object o,Writer out) throws IOException
	    	{
	    	if(o==null)
	    		{
	    		out.write("<span class='jsonNull'>null</span>");
	    		}
	    	else if(o instanceof Boolean)
	    		{
	    		out.write("<span class='jsonBool'>"+o+"</span>");
	    		}
	    	else if(o instanceof Number)
	    		{
	    		out.write("<span class='jsonNumber'>"+o+"</span>");
	    		}
	    	else if(o instanceof String)
	    		{
	    		out.write("<span class='jsonString'>\""+XML.escape(o.toString())+"\"</span>");
	    		}
	    	else if(o instanceof List<?>)
	    		{
	    		List<?> L=List.class.cast(o);
	    		out.write("<span class=\"jsonArray\">[");
	    		for(int i=0;i< L.size();++i)
	    			{
	    			if(i>0) out.write(",");
	    			echo(L.get(i),out);
	    			}
	    		out.write("]</span>");
	    		}
	    	else if(o.getClass().isArray())
	    		{
	    		Object L[]=(Object[])o;
	    		out.write("<span class=\"jsonArray\">[");
	    		for(int i=0;i< L.length;++i)
	    			{
	    			if(i>0) out.write(",");
	    			echo(L[i],out);
	    			}
	    		out.write("]</span>");
	    		}
	    	else if(o instanceof Map<?,?>)
	    		{
	    		Map m=Map.class.cast(o);
	    		out.write("<span class=\"jsonObject\">{");
	    		boolean found=false;
	    		for(Object k:m.keySet())
	    			{
	    			if(found) out.write(",");
	    			found=true;
	    			out.write("<b>\""+XML.escape(k.toString())+"\"</b>:");
	    			echo(m.get(k),out);
	    			}
	    		out.write("}</span>");
	    		}
	    	else
	    		{
	    		out.write(XML.escape(o.toString()));
	    		}
	    	}

    }

